<script setup lang="ts" name="RoleForm">
import { ref, reactive, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Role, RoleCreateRequest, RoleUpdateRequest } from '@/model/user-role-model'
import { createRole, updateRole } from '@/request/user-role-api'

const props = defineProps<{
  visible: boolean
  title: string
  role?: Role | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'saved'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<Partial<RoleCreateRequest & RoleUpdateRequest>>({
  name: '',
  description: '',
  id: 0,
  permission_ids: []
})

// 表单校验规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ]
})

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        
        if (props.role) {
          // 更新角色
          const updateData: RoleUpdateRequest = {
            id: props.role.id,
            name: formData.name || '',
            description: formData.description || ''
          }
          res = await updateRole(props.role.id, updateData)
        } else {
          // 创建角色
          const createData: RoleCreateRequest = {
            name: formData.name || '',
            description: formData.description || '',
            permission_ids: formData.permission_ids || []
          }
          res = await createRole(createData)
        }
        
        if (res.code === 0) {
          ElMessage.success(props.role ? '更新成功' : '创建成功')
          closeDialog()
          emit('saved')
        } else {
          ElMessage.error(res.errorMsg || (props.role ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        console.error(props.role ? '更新角色出错：' : '创建角色出错：', error)
        ElMessage.error(props.role ? '更新失败' : '创建失败')
      }
    }
  })
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 监听角色数据变化
watch(
  () => props.role,
  (newVal) => {
    if (newVal) {
      formData.id = newVal.id
      formData.name = newVal.name
      formData.description = newVal.description || ''
    } else {
      resetForm()
    }
  },
  { immediate: true }
)
</script>

<template>
  <el-dialog
    :title="title"
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :close-on-click-modal="false"
    width="500px"
    @closed="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入角色名称" />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input 
          v-model="formData.description" 
          type="textarea" 
          :rows="4"
          placeholder="请输入角色描述" 
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
